<?php
declare (strict_types=1);

namespace app\common\model;

class Collect extends Base
{
    protected $name = 'collect';
    public function product()
    {
        return $this->hasOne(Product::class, 'id', 'product_id')->field('id,title,price,vip_price,icon,sales');
    }
    //添加收藏
    public static function addCollect($param,$user){
        parent::startTrans();
        try {
            $find=parent::where(['product_id'=>$param['id'],'uid'=>$user->id])->find();
            if(empty($find)){
                $data['create_time']=time();
                $data['uid']=$user->id;
                $data['product_id']=$param['id'];
                parent::create($data);
                return ['code' => 1,'msg'=>'收藏成功！'];
            }else{
                if($param['types']==0){
                    $find->is_del=0;
                    $msg='收藏成功！';
                }else{
                    $find->is_del=1;
                    $msg='取消收藏成功！';
                }
                $find->save();
                return ['code' => 1,'msg'=>$msg];
            }
            parent::commit();
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    //取消收藏
    public static function delCollect($param,$user){
        parent::startTrans();
        try {
            $ids=explode(',',$param['ids']);
            parent::whereIn('id',$ids)->update(['is_del'=>1]);
            parent::commit();
            return ['code' => 1,'msg'=>'取消收藏成功！'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
